package com.gzx.spring.apis.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gzx.spring.apis.utils.xinyisou.RSATool;

import cn.hutool.http.HttpUtil;

public class XinyisouUtil {
	private String appId;
	private String apiUrl;
	private String token;

	public XinyisouUtil appId(String appId) {
		this.appId = appId;
		return this;
	}

	public XinyisouUtil token(String token) {
		this.token = token;
		return this;
	}

	public XinyisouUtil apiUrl(String apiUrl) {
		this.apiUrl = apiUrl;
		return this;
	}

	/**
	 * 私钥(java使用PKCS8版本) 测试环境是统一私钥，而正式环境需要商户这边生成公私钥，上传公钥至taojin@xysl.com 生成公私钥代码，下面有
	 */
	private static final String debugChannelPriKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALMM1nBkwBKv7jgq\n"
			+ "ErC0vAaYuI3GdT0SkIXiZziThNvq3EI14wSVsrW7FUzPlxT8iAQFJKNTHTyddnUU\n"
			+ "bGS1Ggk8kFqw2hMz4CqIMgc/h5YKrwG2zi8tYb4+xsir07MyNQyW0nP9fQgv1urB\n"
			+ "VuLvqIZ+txfq8FO8RxBqOFz5WmMPAgMBAAECgYBJdkXxXVT1FdvOjWyXtb/DkRt/\n"
			+ "h+KISTqkw+yH6PbE6Eqwm71mHylwqK6nkjCxup7vz1Bl9m7zdMOqa9PBShDA83qJ\n"
			+ "Z39FpNwoRuhbYX9jlSu8uPVh7FTfqghA7G9woOUYfOYibWg55RyziaLKlAFTYmps\n"
			+ "dGgM7YqQPkpkhIh4qQJBAOHNqb2exq3R5fKdzQDoUir0NwoGYA7vZBHSCvOLtGt5\n"
			+ "ZzN4gXoTR/VvDAJUUvqED/U+L5JaxzLWkc/TJWR4VRUCQQDK/pYopTlZDbvDSA9O\n"
			+ "2PMnHLs50WgvR/T7WEeU145ahjQBzoFTt9OeUaltbLcZSwvhQ4bWYoZXxALw7ojt\n"
			+ "LWiTAkEAnNRJBmhWubdFLIMpNW4mU6sW5yGSag0exbnK3Wi0wMirQvZ5hx4JJpAg\n"
			+ "GSYUE+bRZpXwWIgwPkEFOQD/wY5KGQJALNAvTiHLm0FQ5jeOSZXTeBr7qjP0kBuO\n"
			+ "lb5TbyR3JLzj1lJEcrruWNEmWiXZ9hd/M+e4aLOvfMik7ZN7XwDbSQJBAKJtL/UT\n"
			+ "uEy+/wmrL+LRu7QrO6wXcnK/rEru3nmHoECpnFKtad4tWJF7ky2T23JO9CiDmrhl\n" + "3h70N8l7TeWWp9I=";
	private static final String onlineChannelPriKey = load("/xinyisou/private.txt");

	private static String load(String name) {
		try {
			return IOUtils.toString(XinyisouUtil.class.getResourceAsStream(name), "UTF-8");
		} catch (Exception e) {
			return "";
		}
	}

	private String exec(String env, Map<String, Object> originParams, String serverUrl)
			throws Exception, UnsupportedEncodingException {
		String orgBizStr = JSON.toJSONString(originParams);
		String key = "";
		if ("debug".equals(env)) {
			key = debugChannelPriKey;
		} else if ("online".equals(env)) {
			key = onlineChannelPriKey;
		}
		String biz = Base64.encodeBase64URLSafeString(RSATool.rsaEncryptByPrivateKey(RSATool.parseRSAPrivateKey(key),
				orgBizStr.getBytes(Charset.forName("UTF-8"))));

		String url = serverUrl + "?app_id=" + appId + "&biz=" + biz;

		String bodyStr = HttpUtil.createGet(url).header("Authorization", token).execute().body();

		JSONObject bodyJson = JSONObject.parseObject(bodyStr);
		String bizData = (String) bodyJson.get("bizData");
		if (bizData != null) {
			final byte[] bytes = RSATool.rsaDecryptByPrivateKey(RSATool.parseRSAPrivateKey(key),
					Base64.decodeBase64(bizData));
			bodyJson.put("bizData", JSONObject.parseObject(new String(bytes, "utf-8")));
		}
		return bodyJson.toJSONString();
	}

	public String mirror_score95(String env, String name, String id, String phone) throws Exception {
		Map<String, Object> originParams = new HashMap<>();
		originParams.put("mobile", phone);
		originParams.put("idcard", id);
		originParams.put("name", name);

		String serverUrl = apiUrl + "/mirror_score95";
		return exec(env, originParams, serverUrl);
	}

	public String puyu_score95s(String env, String name, String id, String phone) throws Exception {
		Map<String, Object> originParams = new HashMap<>();
		originParams.put("mobile", phone);
		originParams.put("idcard", id);
		originParams.put("name", name);

		String serverUrl = apiUrl + "/puyu_score95s";
		return exec(env, originParams, serverUrl);
	}

}
